package controller

import (
	"appService/src/application"
	"appService/src/application/app/appModels"
	"appService/src/application/request"
	"appService/src/authValid"
	"appService/src/authValid/userAuthType"
	"appService/src/authValid/userMap"
	"github.com/gogf/gf/net/ghttp"
)

//Users 用户
type Users struct {
	application.BaseController
}

//getModel 获取控制器对应的 模型
func (*Users) getModel() appModels.IModel {
	return new(appModels.Users)
}

//isRoles 判断用户是否有权限赋予角色给用户
func (this *Users) isRoles(req *request.Request) {
	user := new(appModels.Users)
	req.ParamsAnalyse(user)
	if req.LoginUser.Account.AccountType != userAuthType.SYSTEM_ADMIN {
		for _, id := range user.Roles {
			role := authValid.GetRole(id)
			if role == nil {
				req.JsonError("操作失败，角色不存在")
			} else {
				if role.RoleType >= req.LoginUser.Account.AccountType {
					req.JsonErrorf("您没有权限赋予【%v】角色给该用户", role.RoleName)
				}
			}
		}
	}
}

//Add 添加
func (this *Users) Add(r *ghttp.Request) {
	req := this.NewRequest(r, this.getModel())
	this.isRoles(req)
	req.Add()
}

//Delete 删除
func (this *Users) Delete(r *ghttp.Request) {
	req := this.NewRequest(r, this.getModel())
	req.DeleteHandle(func(ids []string) {
		for _, id := range ids {
			userMap.Remove(id)
		}
	})
}

//Edit 修改
func (this *Users) Edit(r *ghttp.Request) {
	req := this.NewRequest(r, this.getModel())
	this.isRoles(req)
	req.EditHandle(func() {
		user := req.Model.(*appModels.Users)
		if userMap.Exist(user.Uid) {
			lu := userMap.Get(user.Uid)
			account := &lu.Account
			loginUser := new(appModels.UserInfo)
			loginUser.Account = *account
			loginUser.User = *user
			userMap.Set(loginUser)
		}
	})
}

func (this *Users) Get(r *ghttp.Request) {
	this.NewRequest(r, this.getModel()).Get()
}

func (this *Users) ListPaginate(r *ghttp.Request) {
	this.NewRequest(r, this.getModel()).ListPaginate()
}
